package com.lsy.weizhi2.activity;

import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.lsy.weizhi2.JsonObject.Classify;
import com.lsy.weizhi2.JsonObject.NoteList;
import com.lsy.weizhi2.R;
import com.lsy.weizhi2.adapter.ClassifyAdapter;
import com.lsy.weizhi2.adapter.Classify_First_Adapter;
import com.lsy.weizhi2.adapter.HomeNotesAdapter;
import com.lsy.weizhi2.config.Constants;
import com.lsy.weizhi2.config.CostomFlag;
import com.lsy.weizhi2.config.MyHeight;
import com.lsy.weizhi2.config.MyInfo;
import com.lsy.weizhi2.customview.SearchView;
import com.lsy.weizhi2.mybase.MyBaseActivity;
import com.lsy.weizhi2.mybase.MyTitleView;
import com.lsy.weizhi2.myutils.ClassifyFirstCall;
import com.lsy.weizhi2.myutils.SearchCall;
import com.lsy.weizhi2.myutils.TitleViewCall;
import com.lsy.weizhi2.swipetoloadlayout.BaseRecyclerAdapter;
import com.lsy.weizhi2.swipetoloadlayout.OnLoadMoreListener;
import com.lsy.weizhi2.swipetoloadlayout.OnRefreshListener;
import com.lsy.weizhi2.swipetoloadlayout.SuperRefreshRecyclerView;
import com.lsy.weizhi2.utils.MyMethod;
import com.lsy.weizhi2.utils.MyOkHttpUtils;

import org.json.JSONArray;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ClassifyActivity extends MyBaseActivity implements OnRefreshListener, OnLoadMoreListener {
    private Context context;
    private MyTitleView classify_title;
    private SearchView classify_search;
    private int xx;
    private Handler handler = new Handler();
    private RecyclerView classify_first_rv;

    private SuperRefreshRecyclerView classify_second_rv;
    private ClassifyAdapter classifyAdapter;

    private Classify_First_Adapter classify_first_adapter;
    private HomeNotesAdapter homeNotesAdapter;
    private TextView classify_second_title;
    private Gson gson;
    private List<Classify> list;

    private List<NoteList.ListBean>list_n;
    private int pageNo=1;
    private String title;
    private int first=0,second=0;
    private int position;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_classify);
        context = ClassifyActivity.this;
        Init();
    }

    private void Init() {
        gson = new Gson();
        list_n=new ArrayList<>();
        position=getIntent().getIntExtra("position",100);
        first=Integer.parseInt(getIntent().getStringExtra("first")==null?"0":getIntent().getStringExtra("first"));
        second=Integer.parseInt(getIntent().getStringExtra("second")==null?"0":getIntent().getStringExtra("second"));
        title=getIntent().getStringExtra("title");
        Log.i("CustomAdapter","first=="+first+"\nsecond=="+second);
        int size=CostomFlag.list_select.size();
        classify_title = (MyTitleView) findViewById(R.id.classify_title);
        classify_search = (SearchView) findViewById(R.id.classify_search);
        classify_first_rv = (RecyclerView) findViewById(R.id.classify_first_rv);
        classify_second_rv = (SuperRefreshRecyclerView) findViewById(R.id.classify_second_rv);
        classify_second_title = (TextView) findViewById(R.id.classify_second_title);
        LinearLayoutManager manager = new LinearLayoutManager(context);
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        classify_first_rv.setLayoutManager(manager);
        classify_first_adapter = new Classify_First_Adapter(context, list, 10);
        classify_first_rv.setAdapter(classify_first_adapter);

       /* LinearLayoutManager manager1 = new LinearLayoutManager(context);
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        classify_second_rv.setLayoutManager(manager1);
        homeNotesAdapter = new HomeNotesAdapter(context, null);
        classify_second_rv.setAdapter(homeNotesAdapter);*/

        classify_second_rv.init(new LinearLayoutManager(this),this,this);
        classify_second_rv.setRefreshEnabled(true);
        classify_second_rv.setLoadingMoreEnable(true);
        classifyAdapter = new ClassifyAdapter(list_n,context);
        classify_second_rv.setAdapter(classifyAdapter);
        classify_second_rv.showData();
        classifyAdapter.setOnItemClickListener(new BaseRecyclerAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position, long id) {
                Gson gson = new Gson();
                String json = gson.toJson(list_n.get(position));
                MyMethod.toActivity(context, NoteDetail.class, new String[]{"json"}, new String[]{json});
            }
        });

        if(size>position){
            first=CostomFlag.list_select.get(position).getFid();
            second=CostomFlag.list_select.get(position).getId();
            classify_second_title.setText(CostomFlag.list_select.get(position).getName());
        }else{
            classify_second_title.setText("全部微职");
        }
        if(!TextUtils.isEmpty(title)){
            classify_second_title.setText(title);
        }
        classify_title.setTitleViewCall(new TitleViewCall() {
            @Override
            public void Click(View view, int flag) {
                if (flag == TitleViewCall.MORE) {
                    classify_search.setVisibility(View.VISIBLE);
                    classify_search.setHome_addr(MyInfo.UserCity);
                    classify_search.setSearchCall(new SearchCall() {
                        @Override
                        public void Search_S(View view, String address, String content) {
                            MyMethod.showToast(context, content);
                            classify_search.setVisibility(View.GONE);
                        }

                        @Override
                        public void Search_Text(View view) {

                        }
                    });
                }
            }
        });


        classify_first_adapter.setClassifyFirstCall(new ClassifyFirstCall() {
            @Override
            public void onClick(View view, String name,int position) {
                //同时请求服务器更新数据--二级
                second=position;
                pageNo=1;
                Log.i("ClassifyActivity","二级\nfirst=="+first+"\nsecond=="+second);
                classify_second_title.setText(name);
                getNotes(first,second);
            }

            @Override
            public void GetData(String name, int position) {
                //根据first second 重新获取数据，刷新右侧页面--一级
                first=position;
                second=0;
                pageNo=1;
                classify_second_title.setText(name);
                getNotes(first,second);
            }
        });
    }

    @Override
    protected void onStart() {
        super.onStart();
        Log.i("ClassifyActivity", "onStart");

    }
    boolean bottom;
    @Override
    protected void onResume() {
        super.onResume();
        Log.i("ClassifyActivity", "onResume");
        xx = 0;
        ViewTreeObserver vto = classify_title.getViewTreeObserver();
        vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                if (xx < 1) {
                    xx++;
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(classify_title.getLayoutParams());
                            params.height = MyHeight.ACTIONBAR + MyHeight.MyTitleHeight;
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                                classify_title.setLayoutParams(params);
                            }
                        }
                    });
                }
            }
        });

        pageNo=1;
        getClassify();
        getNotes(first,second);
    }
    int dyd;
    float downY,moveY,moveY2;
    boolean down=true;

    private void getClassify(){
        Log.i("ClassifyActivity", "token==" + MyInfo.Token);
        MyOkHttpUtils.getInstance(context).doGet(Constants.GETORDERLIST, null)
                .excute(new MyOkHttpUtils.OKCallBack() {
                    @Override
                    public void onFailure(String message) {

                    }

                    @Override
                    public void onResponse(String message) {
                        if (message != null) {
                            try {
                                JSONArray jsonArray = new JSONArray(message);
                                list = new ArrayList<Classify>();
                                for (int i = 0; i < jsonArray.length(); i++) {
                                    Classify classify = gson.fromJson(jsonArray.getJSONObject(i).toString(), Classify.class);
                                    list.add(classify);
                                }
                                classify_first_adapter.UpData(list, 10);
                            } catch (Exception e) {
                                Log.i("ClassifyActivity", "message=错误==" + message);
                            }
                        }
                    }
                });
    }

    private void getNotes(int first,int second){

        Map<String, String> map = new HashMap<>();
        map.put("pageNo", pageNo+"");
        map.put("pageSize", "10");
        if(first!=0&&second!=0){
            map.put("firstCategoryId",""+first);
            map.put("secondCategoryId",""+second);
        }else if(first!=0&&second==0){
            map.put("firstCategoryId",""+first);
        }
        Log.i("CustomAdapter","first=111="+first+"\nsecond=111="+second);
        MyOkHttpUtils.getInstance(context).doGet(Constants.ORDERLIST, map)
                .excute(new MyOkHttpUtils.OKCallBack() {
                    @Override
                    public void onFailure(String message) {

                    }

                    @Override
                    public void onResponse(String message) {
                        Log.i("ClassifyActivity","message==notes=="+message);
                        if (message != null) {
                            try {
                                NoteList noteList=gson.fromJson(message,NoteList.class);
                                if(pageNo==1){
                                    list_n.clear();
                                }
                                List<NoteList.ListBean>list=noteList.getList();
                                if(list!=null&&list.size()!=0){
                                    list_n.addAll(list);
                                    classifyAdapter.notifyDataSetChanged();
                                    if(pageNo==1){
                                        classify_second_rv.setRefreshing(false);
                                    }else{
                                        classify_second_rv.setLoadingMore(false);
                                        classify_second_rv.moveToPosition(list_n.size() - 1);
                                    }
                                }else{
                                    if(pageNo==1){
                                        classify_second_rv.setRefreshing(false);
                                    }else{
                                        classify_second_rv.setLoadingMore(false);
                                        classify_second_rv.moveToPosition(list_n.size() - 1);
                                    }
                                    pageNo--;
                                }
                            } catch (Exception e) {
                                Log.i("ClassifyActivity", "message=错误=note=" + message);
                            }
                        }
                    }
                });
    }

    @Override
    public void onPause() {
        super.onPause();
        Log.i("ClassifyActivity", "onPause");
        xx = 0;
    }

    @Override
    protected void onStop() {
        super.onStop();
        Log.i("ClassifyActivity", "onStop");
    }

    @Override
    public void onRefresh() {
                pageNo=1;
                getNotes(first,second);
    }

    @Override
    public void onLoadMore() {
        pageNo++;
        getNotes(first,second);
    }
}
